from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from cart import models,cartser
from utils.authontication import JWTAuthenticationss
# Create your views here.

class AddCart(APIView):
    authentication_classes = [JWTAuthenticationss]
    def post(self,request):
        user = request.data.get('user')
        course = request.data.get('course')
        info = models.CartModel.objects.filter(user=user,course=course).first()
        if info:
            return Response({'code':200,'msg':'购物车已存在'})
        else:
            ser = cartser.CartSerializer(data=request.data)
            if ser.is_valid():
                ser.save()
                return Response({'code':200,'msg':'添加成功'})
            else:
                return Response({'code':204,'msg':ser.errors})



class CartList(APIView):
    authentication_classes = [JWTAuthenticationss]
    def get(self,request):
        user = request.query_params.get('user')
        datalist = models.CartModel.objects.filter(user=user)
        ser = cartser.CartSerializer(datalist,many=True)

        cartdata = []
        total = 0
        selectnum = 0
        for i in datalist:
            course = {}
            course['id'] = i.id#购物车id
            course['courseid'] = i.course.id#课程id
            course['name'] = i.course.name#课程名称
            course['price'] = i.course.price#课程价格
            course['img'] = str(i.course.image)#课程图片
            course['selected'] = i.selcted#是否选中
            course['addtime'] = i.createtime#添加时间
            cartdata.append(course)
            if i.selcted:
                selectnum += 1
                total += i.course.price
        return Response({'msg':'ok','cartlist':cartdata,'total':total,'selectnum':selectnum})

